package com.wxzz.elearing.pay.wx.mini;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wxzz.elearing.pay.entity.PayLog;
import com.wxzz.elearing.pay.mapper.PayLogMapper;
import com.wxzz.elearning.common.constants.WxPayConstants;
import com.wxzz.elearning.common.utils.YmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class WxToPay {

    private final static Logger logger = LoggerFactory.getLogger(WxToPay.class);

    //获取微信支付签名
    public static String payMsg(String ipaddress, String openid, String serialid, String payMoney) {
        try {
            if (ipaddress == null || "".equals(ipaddress) || "null".equals(ipaddress)) {
                return "";
            }
            if (openid == null || "".equals(openid) || "null".equals(openid)) {
                return "";
            }
            if (serialid == null || "".equals(serialid) || "null".equals(serialid)) {
                return "";
            }
            if (payMoney == null || "".equals(payMoney) || "null".equals(payMoney)) {
                return "";
            } else {
                BigDecimal bdPayMoney = new BigDecimal(payMoney);
                BigDecimal bdmin = new BigDecimal("0.01");
                if (bdmin.compareTo(bdPayMoney) > 0) {
                    return "";
                } else {
                    payMoney = bdPayMoney.multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP).toPlainString();
                }
            }
        } catch (Exception e) {
            return "";
        }
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("timeStamp", "");
        map.put("nonceStr", "");
        map.put("package", "");
        map.put("signType", "");
        map.put("paySign", "");
        String appid = WxPayConstants.WX_APPID;
        String body = "精工支付";
        String notify_url = YmlUtil.getBootstrapYml("pay.wx.mini-return-url").toString();
        String trade_type = "JSAPI";
        String nonce_str = ShareFunction.getRandomString(25);
        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("appid", appid);
        packageParams.put("mch_id", WxPayConstants.MCH_ID);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("body", body);//商品简单描述
        //packageParams.put("attach", attach);//附加数据，在查询API和支付通知中原样返回，可作为自定义参数使用
        packageParams.put("out_trade_no", serialid);//商户订单号
        packageParams.put("total_fee", payMoney);//订单总金额，单位为分
        packageParams.put("spbill_create_ip", ipaddress);//APP和网页支付提交用户端ip
        packageParams.put("notify_url", notify_url);//回调地址
        packageParams.put("trade_type", trade_type);//交易类型
        packageParams.put("openid", openid);//用户openid
        RequestHandler reqHandler = new RequestHandler(null, null);
        reqHandler.init(appid, WxPayConstants.WX_SECRET, WxPayConstants.WX_KEY);
        String sign = reqHandler.createSign(packageParams);
        String xml = "<xml>" + "<appid>" + appid + "</appid>"
                + "<mch_id>" + WxPayConstants.MCH_ID + "</mch_id>"
                + "<nonce_str>" + nonce_str + "</nonce_str>"
                + "<sign><![CDATA[" + sign + "]]></sign>"
                + "<body><![CDATA[" + body + "]]></body>"
                + "<out_trade_no>" + serialid + "</out_trade_no>"
                + "<total_fee>" + payMoney + "</total_fee>"
                + "<spbill_create_ip>" + ipaddress + "</spbill_create_ip>"
                + "<notify_url>" + notify_url + "</notify_url>"
                + "<trade_type>" + trade_type + "</trade_type>"
                + "<openid>" + openid + "</openid>" + "</xml>";
        try {
            reqHandler.genPackage(packageParams);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        String prepay_id = "";
        try {
            prepay_id = new GetWxOrderno().getPayNo(createOrderURL, xml);
            if ("".equals(prepay_id)) {
                System.out.println("统一支付接口获取预支付订单出错");
                System.out.println("XML值：");
                System.out.println(xml);
                System.out.println("可前往https://pay.weixin.qq.com/wiki/doc/api/micropay.php?chapter=20_1 签名校验工具校验");
                System.out.println("商户Key是API密钥，如果和微信的在线签名工具一致，说明程序没有错误，确定是API密钥错误。");
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        SortedMap<String, String> finalpackage = new TreeMap<String, String>();
        String timestamp = Sha1Util.getTimeStamp();
        String packages = "prepay_id=" + prepay_id;
        finalpackage.put("appId", appid);
        finalpackage.put("timeStamp", timestamp);
        finalpackage.put("nonceStr", nonce_str);
        finalpackage.put("package", packages);
        finalpackage.put("signType", "MD5");
        reqHandler.init(appid, WxPayConstants.WX_SECRET, WxPayConstants.WX_KEY);
        String finalsign = reqHandler.createSign(finalpackage);
		/*String str = "timestamp:\""
				+ timestamp // 这里的也是小写~~
				+ "\",nonceStr:\"" + nonce_str + "\",package:\"" + packages
				+ "\",signType: \"MD5" + "\",paySign:\"" + finalsign + "\"";*/
        map.put("timeStamp", timestamp);
        map.put("nonceStr", nonce_str);
        map.put("package", packages);
        map.put("signType", "MD5");
        map.put("paySign", finalsign);

        String jsonString = JSON.toJSONString(map);
        //System.out.println(jsonString);
        return jsonString;
    }


    //获得支付回调商户订单号
    public static String getPaySerialid(HttpServletRequest request, PayLogMapper payLogMapper) {
        try {

            String serialid = "";
            request.setCharacterEncoding("UTF-8");
            BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            String res = sb.toString();
            if (res == null || "".equals(res) || "null".equals(res)) {
                return "";
            } else {
                logger.info("订单回调解析的数据:[{}]", res);
                if (res.indexOf("<result_code><![CDATA[SUCCESS]]></result_code>") >= 0) {
                    int index1 = res.indexOf("<out_trade_no><![CDATA[");
                    int index2 = res.indexOf("]]></out_trade_no>");
                    if (index1 >= 0 && index2 >= 0) {
                        serialid = res.substring(index1 + 23, index2);
                    }
                }
            }
            //==================支付日志================================
            PayLog payLog = payLogMapper.selectOne(new LambdaQueryWrapper<PayLog>()
                    .eq(PayLog::getOrderNum, serialid));
            payLog.setNotifyInfo(res);
            payLog.setNotifyTime(LocalDateTime.now());
            payLogMapper.updateById(payLog);
            return serialid;
        } catch (Exception e) {
            logger.error("订单回调发生错误:[{}]", e.getMessage());
        }
        return null;
    }

    //企业付款至用户
//	public static String refundToUser(String ipaddress,String openid,String serialid,String tradeNum,String desc){
//		try{
//			if(ipaddress==null||"".equals(ipaddress)||"null".equals(ipaddress)){
//				return "ip地址为空";
//			}
//			if(openid==null||"".equals(openid)||"null".equals(openid)){
//				return "openid为空";
//			}
//			if(serialid==null||"".equals(serialid)||"null".equals(serialid)){
//				return "交易单号为空";
//			}
//			if(desc==null||"".equals(desc)||"null".equals(desc)){
//				return "描述为空";
//			}
//			if(tradeNum==null||"".equals(tradeNum)||"null".equals(tradeNum)){
//				return "转账数量为空";
//			}else{
//				BigDecimal bdPayMoney = new BigDecimal(tradeNum);
//				BigDecimal bdmin = new BigDecimal("1");
//				if(bdmin.compareTo(bdPayMoney)>0){
//					return "";
//				}else{
//					tradeNum = bdPayMoney.multiply(new BigDecimal(100)).setScale(0,BigDecimal.ROUND_HALF_UP).toPlainString();
//				}
//			}
//
//			String mch_appid = DefaultData.wx_gz_appid;//商户账号appid
//			String nonce_str = ShareFunction.getRandomString(25);//随机字符串
//			String partner_trade_no = serialid;
//			String check_name = "NO_CHECK";//不校验真实姓名，设置为FORCE_CHECK需要校验
//			String amount = tradeNum;
//			SortedMap<String, String> packageParams = new TreeMap<String, String>();
//			packageParams.put("mch_appid", mch_appid);
//			packageParams.put("mchid", DefaultData.wx_mch_id);
//			packageParams.put("nonce_str", nonce_str);
//			packageParams.put("partner_trade_no", partner_trade_no);
//			packageParams.put("openid", openid);
//	        packageParams.put("check_name", check_name);
//	        packageParams.put("amount", amount);
//	        packageParams.put("desc", desc);
//	        packageParams.put("spbill_create_ip", ipaddress);
//			RequestHandler reqHandler = new RequestHandler(null, null);
//			reqHandler.init(mch_appid, DefaultData.wx_gz_appsecret, DefaultData.wx_gz_key);
//			String sign = reqHandler.createSign(packageParams);
//			String xml = "<xml>"
//					+ "<mch_appid>" + mch_appid + "</mch_appid>"
//					+ "<mchid>" + DefaultData.wx_mch_id + "</mchid>"
//					+ "<nonce_str>" + nonce_str + "</nonce_str>"
//					+ "<partner_trade_no>" + partner_trade_no + "</partner_trade_no>"
//					+ "<openid>" + openid + "</openid>"
//					+ "<check_name>" + check_name + "</check_name>"
//					+ "<amount>" + amount + "</amount>"
//					+ "<desc>" + desc + "</desc>"
//					+ "<spbill_create_ip>" + ipaddress + "</spbill_create_ip>"
//					+ "<sign><![CDATA[" + sign + "]]></sign>"
//					+ "</xml>";
//			try{
//				reqHandler.genPackage(packageParams);
//			}catch(Exception e){
//				e.printStackTrace();
//			}
//			String createOrderURL = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
//			String refundRes = new GetWxOrderno().getRefund(createOrderURL, xml);
//			return refundRes;
//		}catch (Exception e) {
//			return "";
//		}
//	}


}
